<?php

namespace App\Http\Controllers\Api;

use App\Common\Libs\ArrayHelper;
use App\Consts\GlobalConst;
use App\Consts\GlobalPackageConst;
use App\Exceptions\Error;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class PackageController extends BaseController
{
    public $validate = [
        "add" => ["rules" => [
            "name" => "sometimes|required|string|max:90",
            "description" => "max:400",
            "is_public" => "sometimes|required|integer|in:0,1",
        ]],
        "del" => ["rules" => [
            "id" => "required|string|max:24",
        ]],
        "edit" => ["rules" => [
            "id" => "required|string|max:24",
            "name" => "sometimes|required|string|max:90",
            "description" => "max:400",
            "is_public" => "integer|in:0,1",
        ]],
        "getDetail" => ["rules" => [
            "id" => "required|string|max:1000",
        ]],
        "getList" => ["rules" => [
            "last_id" => "max:24",
            "user_id" => "sometimes|required|string|max:24",
            "target_id" => "sometimes|required|string|max:24",
        ]],
        "moreList" => ["rules" => [
            "id" => "required|string|max:24",
        ]],
        "targetList" => ["rules" => [
            "package_id" => "required|string|max:24",
        ]],
    ];

    /**
     * @path /package/quick-list
     * @category 桌面
     * @title 【有备注】收藏夹列表
     * @method POST
     * @params [{"name":"url","type":"text","required":1,"example":"","desc":"一键收藏的url"},{"name":"last_id","type":"text","required":0,"example":"","desc":"【翻页时必传】当前页最后一条记录的ID"}]
     * @resBody {"success":true,"statusCode":200,"message":"操作成功","result":{"have_more":true,"list":[{"id":"收藏夹ID","user_id":"用户ID","name":"收藏夹名称","description":"收藏夹描述","total":"收藏夹内容总数","is_default":1,"is_deleted":0,"is_public":1,"updated_at":"收藏夹最后更新时间"}]}}
     * @description 1.【前端】此接口发生于点击一键收藏并接口成功返回后
     */
    public function quickList(Request $request)
    {
        $params = $request->post();

        $currentUserId = $this->getCurrentUserId();

        $searchParams = [
            'page' => !empty($params['page']) ? $params['page'] - 1 : 0,
            'current_user_id' => $currentUserId,
            'user_id' => $currentUserId,
        ];

        $result = service()->PackageService->getUserCollectPackageList($searchParams);

        return $this->apiReturn($result);
    }

    /**
     * @path /package/list
     * @category 收藏夹
     * @title 列表
     * @method POST
     * @params [{"name":"target_id","type":"text","required":0,"example":"","desc":"主体ID，当查看主体详情时此字段必传"},{"name":"user_id","type":"text","required":0,"example":"","desc":"用户ID，当查看他人时此字段必传"},{"name":"last_id","type":"text","required":0,"example":"","desc":"【翻页时必传】当前页最后一条记录的ID"}]
     * @resBody {"success":true,"statusCode":200,"message":"操作成功","result":{"have_more":true,"list":[{"id":"收藏夹ID","user_id":"用户ID","name":"收藏夹名称","description":"收藏夹描述","total":"收藏夹内容总数","is_default":1,"is_deleted":0,"is_public":1,"updated_at":"收藏夹最后更新时间"}]}}
     */
    public function getList(Request $request)
    {
        $params = $request->post();

        $currentUserId = $this->getCurrentUserId();
        // 收藏某主体时 - 收藏夹列表
        if (array_key_exists('target_id', $params) && !array_key_exists('user_id', $params)) {
            $searchParams = [
                'page' => !empty($params['page']) ? $params['page'] - 1 : 0,
                'current_user_id' => $currentUserId,
                'user_id' => $currentUserId,
                'is_public' => [GlobalPackageConst::IS_PUBLIC, GlobalPackageConst::IS_NOT_PUBLIC],
            ];
            if (!empty($params['last_id'])) {
                $searchParams = ArrayHelper::merge($searchParams, [
                    'last_id' => $params['last_id']
                ]);
            }
            $collectPackageList = service()->PackageService->getCollectPackageListByTargetId($searchParams);

            $collect = service()->CollectService->getNormalCollectByTarget($currentUserId, $params['target_id']);
            $result = ArrayHelper::merge($collectPackageList, [
                'package_id' => $collect->package_id ?? 0
            ]);
        } else {
            $userId = !empty($params['user_id']) ? $params['user_id'] : $this->getCurrentUserId();
            // 个人中心 - 收藏夹列表
            $searchParams = [
                'page' => !empty($params['page']) ? $params['page'] - 1 : 0,
                'current_user_id' => $currentUserId,
                'user_id' => $userId,
            ];
            if (!empty($params['last_id'])) {
                $searchParams = ArrayHelper::merge($searchParams, [
                    'last_id' => $params['last_id']
                ]);
            }
            $result = service()->PackageService->getUserCollectPackageList($searchParams);
        }

        return $this->apiReturn($result);
    }

    /**
     * @path /package/more-list
     * @category 收藏夹
     * @title 侧边栏更多收藏夹列表
     * @method POST
     * @params [{"name":"id","type":"text","required":1,"example":"","desc":"当前被查看收藏夹ID"}]
     * @resBody {"success":true,"statusCode":200,"message":"操作成功","result":{"have_more":true,"list":[{"id":"收藏夹ID","user_id":"用户ID","name":"收藏夹名称","description":"收藏夹描述","total":"收藏夹内容总数","is_default":1,"is_deleted":0,"is_public":1,"updated_at":"收藏夹最后更新时间"}]}}
     */
    public function moreList(Request $request)
    {
        $params = $request->post();

        $indexCollectPackage = service()->PackageService->getCollectPackageById($params['id']);
        $searchParams = [
            'seen' => $params['id'],
            'user_id' => $indexCollectPackage->user_id,
            'current_user_id' => $this->getCurrentUserId(),
            'page_size' => GlobalConst::PAGE_COUNT_FIVE,
            'is_public' => GlobalPackageConst::IS_PUBLIC,
            'not_create_default' => true
        ];
        $collectPackageList = service()->PackageService->getUserCollectPackageList($searchParams);

        return $this->apiReturn($collectPackageList);
    }

    /**
     * @path /package/target-list
     * @category 收藏夹
     * @title 内容列表
     * @method POST
     * @params [{"name":"package_id","type":"text","required":1,"example":"","desc":"收藏夹ID"},{"name":"tab_type","type":"text","required":0,"example":"","desc":"全部all【默认】，文章article，笔记note"},{"name":"user_id","type":"text","required":0,"example":"","desc":"用户ID，当查看他人时此字段必传"},{"name":"last_id","type":"text","required":0,"example":"","desc":"【翻页时必传】当前页最后一条记录的ID"}]
     * @resBody {"success":true,"statusCode":200,"message":"操作成功","result":{"have_more":false,"list":[{"id":"笔记ID","collect_id":"收藏ID","type":"笔记类型，1文章笔记，2划线笔记，3随手记","user_id":"用户ID","article_id":"文章ID","is_deleted":0,"is_public":1,"created_at":"创建时间戳","package_id":"收藏夹ID","is_collect":false,"target_type":"主体类型","content":"笔记内容","selected":"文章节选","user":{"id":"用户ID","nickname":"用户昵称","avatar":"用户头像，如1.jpg"},"article":{"id":"文章ID","author_id":"作者ID","cover_url":"文章封面图，如1.jpg","title":"文章标题","description":"文章描述","type":1,"is_deleted":0,"is_shield":0,"created_at":"创建时间戳"},"count":{"like":"点赞数","collect":"收藏数"}},{"id":"文章ID","author_id":"作者ID","cover_url":"文章封面图，如1.jpg","title":"文章标题","description":"文章描述","type":"文章类型，1推荐，2原创","is_deleted":0,"is_shield":0,"created_at":"创建时间戳","collect_id":"收藏ID","package_id":"收藏夹ID","target_type":1}]}}
     */
    public function targetList(Request $request)
    {
        $params = $request->post();

        $searchParams = [
            'current_user_id' => $this->getCurrentUserId(),
            'package_id' => $params['package_id'],
            'tab_type' => $params['tab_type'] ?? GlobalPackageConst::TAB_TYPE_ALL,
        ];
        if (array_key_exists('last_id', $params)) {
            $searchParams['last_id'] = $params['last_id'];
        }

        $collectPackageList = service()->PackageService->getCollectPackageTargetList($searchParams);

        return $this->apiReturn($collectPackageList);
    }

    /**
     * @path /package/add
     * @category 收藏夹
     * @title 新增
     * @method POST
     * @params [{"name":"name","type":"text","required":1,"example":"","desc":"收藏夹名称"},{"name":"is_public","type":"text","required":0,"example":"","desc":"是否公开，0私密，1公开"},{"name":"description","type":"text","required":0,"example":"","desc":"收藏夹描述"}]
     * @resBody {"success":true,"statusCode":200,"result":{"id":"24位收藏夹ID","name":"这是某用户新建的收藏夹","description":"这是收藏夹描述","total":"内容数","is_default":0,"is_public":1,"is_deleted":0},"message":"OK"}
     */
    public function add(Request $request)
    {
        $params = $request->all();
        $loadData = [
            'user_id' => $this->getCurrentUserId(),
            'name' => $params['name'] ?? '',
            'description' => $params['description'] ?? '',
            'is_public' => $params['is_public'] ?? GlobalPackageConst::IS_PUBLIC,
        ];

        $createCollectPackageResult = service()->PackageService->createCollectPackage($loadData);

        return $this->apiReturn($createCollectPackageResult);
    }

    /**
     * @path /package/del
     * @category 收藏夹
     * @title 删除
     * @method POST
     * @params [{"name":"id","type":"text","required":1,"example":"","desc":"收藏夹ID"}]
     * @resBody {"success":true,"statusCode":200,"result":true,"message":"OK"}
     */
    public function del(Request $request)
    {
        $params = $request->all();

        $delCollectPackageResult = service()->PackageService->delCollectPackage($this->getCurrentUserId(), $params['id']);

        return $this->apiReturn($delCollectPackageResult);
    }

    /**
     * @path /package/edit
     * @category 收藏夹
     * @title 修改
     * @method POST
     * @params [{"name":"id","type":"text","required":1,"example":"","desc":"收藏夹ID"},{"name":"name","type":"text","required":0,"example":"","desc":"收藏夹名称"},{"name":"is_public","type":"text","required":0,"example":"","desc":"是否公开，0私密，1公开"},{"name":"description","type":"text","required":0,"example":"","desc":"收藏夹描述"}]
     * @resBody {"success":true,"statusCode":200,"result":{"id":"24位收藏夹ID","name":"这是某用户新建的收藏夹","description":"这是收藏夹描述","total":"内容数","is_default":0,"is_public":1,"is_deleted":0},"message":"OK"}
     */
    public function edit(Request $request)
    {
        $params = $request->post();

        $loadData = [
            'package_id' => $params['id'],
            'user_id' => $this->getCurrentUserId(),
        ];
        if (array_key_exists('name', $params)) {
            $loadData['name'] = $params['name'];
        }
        if (array_key_exists('description', $params)) {
            $loadData['description'] = $params['description'];
        }
        if (array_key_exists('is_public', $params)) {
            $loadData['is_public'] = $params['is_public'];
        }

        $collectPackage = service()->PackageService->updateCollectPackage($loadData);

        return $this->apiReturn($collectPackage);
    }

    /**
     * @path /package/get-detail
     * @category 收藏夹
     * @title 详情
     * @method POST
     * @params [{"name":"id","type":"text","required":1,"example":"","desc":"收藏夹ID"}]
     * @resBody {"success":true,"statusCode":200,"result":{"id":"24位收藏夹ID","name":"收藏夹名称","description":"收藏夹描述","total":"内容数","is_default":0,"is_public":1,"is_deleted":0},"message":"OK"}
     */
    public function getDetail(Request $request)
    {
        $params = $request->post();

        // 获取收藏夹信息
        $collectPackage = service()->PackageService->getCollectPackageById($params['id']);
        if (!$collectPackage) {
            return $this->apiReturn(Error::handle());
        }

        // 不是本人查看收藏夹时，需要验证收藏夹状态
        if ($this->getCurrentUserId() !== $collectPackage->user_id && $collectPackage->is_deleted == GlobalConst::IS_DELETED) {
            return $this->apiReturn(Error::handle(lang('Collect package is disable')));
        }

        return $this->apiReturn($collectPackage->commonFormat());
    }
}
